<template>
  <div>
    <van-cell @click="getSuggestSearch(item)"
      v-for="(item,index) in suggestions"
      :key="index" icon="search">
      <span slot="title"
        v-html="formatSearch(item)"></span>
    </van-cell>

  </div>
</template>

<script>
import { debounce } from 'lodash'
import { getSearchSuggestion } from '@/api/search.js'
export default {
  data () {
    return {
      setId: null,
      suggestions: [],
      isShow: true
    }
  },
  props: {
    value: {
      type: String,
      required: true
    }
  },
  methods: {
    getSuggestSearch (item) {
      this.$emit('search', item)
      // const reg = new RegExp(this.value, 'gi')
      // this.$emit('search', item.replace(reg, this.value))
    },
    formatSearch (item) {
      const reg = new RegExp(this.value, 'gi')
      return item.replace(reg, `<span style="color:red">${this.value}</span>`)
    },
    async loadSearchSuggestion () {
      try {
        const { data: res } = await getSearchSuggestion(this.value)
        this.suggestions = res.data.options
      } catch (err) {
        this.$toast('获取建议失败')
      }
    }
  },
  computed: {},
  watch: {
    value: {
      immediate: true,
      handler: debounce(function (nval) {
        if (!this.isShow) return
        this.loadSearchSuggestion()
      }, 900)
      // handler (nval) {
      //   clearTimeout(this.setId)
      //   this.setId = setTimeout(() => {
      //     console.log(nval)
      //   }, 900)
      // }
    }
  },
  filters: {},
  components: {},
  created () { },
  mounted () { },
  beforeDestroy () {
    this.isShow = false
  }
}
</script>

<style scoped lang='less'>
</style>
